package messenger.domain;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpSession;

import messenger.context.Constants;

public class User {
	private static Integer lastId = 0;
	
	private Integer id;
	private String name;
	private List<Message> messageStack;
	
	private ChatSession chatSession;
	
	public User() {
		synchronized (lastId) {
			id = lastId;
			lastId++;
		}
		
		messageStack = new ArrayList<Message>();
	}
	
	public User(int id) {
		this.id = id;
		messageStack = new ArrayList<Message>();
	}
	
	
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getUniqueName() {
		return this.id + this.name;
	}
	public Message[] consumeMessages() {
		Message[] messages = null;
		
		synchronized (messageStack) {
			messages = messageStack.toArray(new Message[0]);
			
			messageStack.clear();			
		}
		
		return messages;
	}
	public void addMessage(Message message) {
		this.messageStack.add(message);
	}
	
	public ChatSession getChatSession() {
		return chatSession;
	}
	
	public void setChatSession(ChatSession chatSession) {
		this.chatSession = chatSession;
	}
	
	
	//------------------------------- statics -----------------------------------
	public static void addUserToSession(HttpSession session, User user) {
		session.setAttribute(Constants.USER_ATTRIBUTE, user);
	}
	
	public static User getUserFromSession(HttpSession session) {	
		return (User)session.getAttribute(Constants.USER_ATTRIBUTE);
	}
	
	public static boolean isAutorizedUser(HttpSession session) {
		User user = getUserFromSession(session);
		
		return user != null && user.getId() != null;
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof User))
			return false;
		User other = (User) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
}
